package com.itfreer.data.service.report;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.itfreer.data.report.service.BaseReportService;
import com.itfreer.utils.json.JsonUtils;

/**
 * 统计报表基本rest服务 注:目前只支持单表统计。
 * 
 * @author cai
 *
 * @param <T>
 */
public abstract class RestReportService<T> {

	protected abstract BaseReportService<T> getService();

	@SuppressWarnings({ "rawtypes" })
	private Class getTClass() {
		Class entityClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		return entityClass;
	}

	@SuppressWarnings("unchecked")
	private T getNewT() {
		T jEntity = null;
		try {
			jEntity = (T) getTClass().newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return jEntity;
	}

	/**
	 * 获取当前条件下的数据行总数
	 * 
	 * @param where
	 *            查询条件
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@POST
	@Path("/getReports")
	@Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
	public List getReports(String data) throws IOException {
		HashMap<String, Object> args = getRestParam(data);
		String whereString = null;
		if (args != null) {
			if (args.containsKey("where") && args.get("where") != null)
				whereString = args.get("where").toString();
		}
		HashMap where = JsonUtils.toBean(whereString, HashMap.class);
		T entity = this.getNewT();
		return getService().getReports(entity, where, "", "");
	}

	/**
	 * 解决请求参数问题
	 * 
	 * @param data
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static HashMap<String, Object> getRestParam(String data) {
		HashMap<String, Object> args = null;
		if (data == null || "".equals(data.trim()))
			return args;
		// 解决不同浏览器返回传递参数不一致问题-s-
		try {
			args = JsonUtils.toBean(data, HashMap.class);

		} catch (Exception e) {
			try {
				String ENCODE = "UTF-8";
				data = java.net.URLDecoder.decode(data, ENCODE);
				if (data != null && !"".equals(data.trim())) {
					String[] lst = data.split("&");
					args = new HashMap<String, Object>();
					for (String item : lst) {
						if (item == null || "".equals(item.trim()))
							continue;
						String[] ivalue = item.split("=");
						if (ivalue != null) {
							if (ivalue.length > 1) {
								args.put(ivalue[0], ivalue[1]);
							} else {
								args.put(ivalue[0], null);
							}
						}

					}
				}
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		// 解决不同浏览器返回传递参数不一致问题-e-
		return args;
	}
}
